package com.easy.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.easy.common.util.Result;
import com.easy.common.util.SYS;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;

import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.List;
@Component//添加过滤器
public class GatewayGlobalFilter implements GlobalFilter, Ordered {
    //白名单(无论是否登录都有)
    private static final List<String> ALLOWED_PATHS =
            Arrays.asList("/user/login/userDoLogin", "/user/register","/user/login/captcha","/user/login/adminDoLogin","/user/login/logininfo","/user/login/send-reset-code"
                    ,"/user/login/verify-reset-code","/user/login/reset-password-by-email","/user/upload/file");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        URI uri= request.getURI();
        String path = uri.getPath();
        System.out.println("path---------------"+path);
        if (ALLOWED_PATHS.contains(path)){
            //如果白名单中有就放行
            return chain.filter(exchange);
        }
        //验证有没有登录
        //获取token
        String token = request.getHeaders().getFirst(SYS.TOKEN_AUTHORIZATION);
        //判断token是否为空，是否有效，如果认证模块，在此通过Dubbo服务获取token是否有效
        if(token==null){
            return unauthorizedResponse(exchange, Result.fail(401, "未认证"));
        }
        //验证token通过就放行
        return chain.filter(exchange);
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, Result result) {

        String json= JSON.toJSONString(result);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");
        return response.writeWith(Mono.just(response.bufferFactory()
                .wrap(json.getBytes())));
    }

    @Override
    //这个方法确定过滤器的执行顺序，数字越小越先执行
    public int getOrder() {
        return 0;
    }
}
